package be.rivendale.renderer.mk2.remote;

import be.rivendale.renderer.mk2.Consumer;
import be.rivendale.renderer.mk2.LoadBalancer;
import be.rivendale.renderer.mk2.data.Rectangle;
import be.rivendale.renderer.mk2.data.Segment;

import java.net.Socket;
import java.util.List;

public class Transmitter extends Thread implements Consumer {
    private SocketStreamer socketStreamer;
    private LoadBalancer loadBalancer;

    public Transmitter(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
        start();
    }

    @Override
    public void run() {
        socketStreamer = openConnection();
        while(true) {
            List<Rectangle> rectangles = socketStreamer.<List<Rectangle>>read();
            loadBalancer.dispatch(rectangles);
        }
    }

    @Override
    public synchronized void onConsumerStarted() {
    }

    @Override
    public void onSegmentComplete(Segment segment) {
        segment.mark();
        socketStreamer.write(segment);
    }

    private SocketStreamer openConnection() {
        System.out.print("Connecting to master... ");
        SocketStreamer socketStreamer = new SocketStreamer(establishSocketConnectionToMaster());
        System.out.println("Connected.");
        return socketStreamer;
    }

    private Socket establishSocketConnectionToMaster() {
        try {
            return new Socket("192.168.0.9", 1507);
        } catch(Throwable exception) {
            System.out.print("Failed, trying again... ");
            return establishSocketConnectionToMaster();
        }
    }
}
